package com.fuhailiu.opengl.renders;

import javax.microedition.khronos.opengles.GL10;

import android.content.Context;
import android.view.SurfaceHolder;

import com.fuhailiu.opengl.utils.LogUtil;
import com.fuhailiu.opengl.view.GLViewGroup;
import com.fuhailiu.opengl.widget.GLTexture2D;

public class RenderTexture2D extends AbsRender implements Runnable {

	private final String TAG = getClass().getSimpleName();

	private GLTexture2D mGLTexture2D;
	private Thread mTranslateThread = null;

	public RenderTexture2D(Context context) {
		super(context);
	}

	@Override
	public void onSurfaceChanged(GL10 gl, int width, int height) {
		super.onSurfaceChanged(gl, width, height);

		maxTranslateX = 1.0f * mSurfaceWidth / mSurfaceHeight - mGLTexture2D.x;
		maxTranslateY = 1.0f - mGLTexture2D.y;
		LogUtil.LogD(TAG, "onSurfaceChanged   maxTranslateX = " + maxTranslateX + ", maxTranslateY = " + maxTranslateY);

		if (null == mTranslateThread) {
			mbStop = false;
			mTranslateThread = new Thread(this);
			mTranslateThread.start();
		}
	}

	@Override
	protected GLViewGroup makeWorld(Context context) {
		LogUtil.LogD(TAG, "makeWorld   <---");

		GLViewGroup layout = new GLViewGroup(context);

		mGLTexture2D = new GLTexture2D(context);
		layout.addView(mGLTexture2D);

		LogUtil.LogD(TAG, "makeWorld   --->");

		return layout;
	}

	@Override
	public void onSurfaceDestroyed(SurfaceHolder holder) {
		super.onSurfaceDestroyed(holder);
		mbStop = true;
	}

	private boolean mbStop = false;
	private volatile float stepX = 0.01f;
	private volatile float stepY = 0.01f;
	private float maxTranslateX;
	private float maxTranslateY;

	@Override
	public void run() {
		while (!mbStop) {
			try {
				Thread.sleep(10);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			float translateX = mGLTexture2D.mTranslateX;
			float translateY = mGLTexture2D.mTranslateY;
			translateX += stepX;
			translateY += stepY;
			if (Math.abs(translateX) > maxTranslateX) {
				translateX = (translateX > 0 ? 1.0f : -1.0f) * maxTranslateX;
				stepX *= -1.0f;
			}
			if (Math.abs(translateY) > maxTranslateY) {
				translateY = (translateY > 0 ? 1.0f : -1.0f) * maxTranslateY;
				stepY *= -1.0f;
			}
			mGLTexture2D.mTranslateX = translateX;
			mGLTexture2D.mTranslateY = translateY;
		}
	}

}
